//
//  RankTableViewCell.m
//  SoundPill
//
//  Created by 宋旭东 on 15/10/20.
//  Copyright © 2015年 宋旭东. All rights reserved.
//

#import "RankTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "AFNetworking.h"
#import "UIViewExt.h"
#import "JCAlertView.h"
#import "AppDelegate.h"
@interface RankTableViewCell ()
{
    UIView *bottomLine;
}
@property (nonatomic, copy) NSString *userId; 
@end

@implementation RankTableViewCell
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    
    if (self) {
        // 创建子视图
        [self createSubviews];
    }
    return self;
}

- (void)awakeFromNib {
    // Initialization code
}

- (void)createSubviews
{
    self.avatar = [[UIImageView alloc] initWithFrame:CGRectZero];
    [self addSubview:_avatar];
    
    self.name = [[UILabel alloc] initWithFrame:CGRectZero];
    self.name.font = [UIFont fontWithName:@"Helvetica-Bold" size:15.0f];
    [self addSubview:_name];
    
    self.Signature = [[UILabel alloc] initWithFrame:CGRectZero];
    _Signature.font = [UIFont systemFontOfSize:14];
    _Signature.textColor = [UIColor grayColor];
    _Signature.numberOfLines = 1;
    [self addSubview:_Signature];
    
    self.sexImg = [[UIImageView alloc] initWithFrame:CGRectZero];
    [self addSubview:_sexImg];
    // 关系
    self.attention = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.attention setFrame:CGRectZero];
    [self.attention addTarget:self action:@selector(attention:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.attention];
    self.relation = [[UILabel alloc] initWithFrame:CGRectZero];
    _relation.textAlignment = NSTextAlignmentCenter;
    [self.relation setFont:[UIFont fontWithName:@"Helvetica-Bold" size:10.0f]];
    [self.contentView addSubview:self.relation];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    [_avatar setImageWithURL:[NSURL URLWithString:_rankModel.avatar] placeholderImage:[UIImage imageNamed:@"default_head"]];
    _avatar.frame = CGRectMake(12, 12, self.frame.size.height - 24, self.frame.size.height - 24);
    
    _name.text = _rankModel.username;
    CGSize nameSize = [self changeWorkNameFrame:_name.text font:_name.font];
    if ([UIScreen mainScreen].bounds.size.width == 320) {
        _name.frame = CGRectMake(_avatar.frame.origin.x + _avatar.frame.size.width + 10, 10, 3*_avatar.frame.size.width, nameSize.height + 2);
    } else {
        _name.frame = CGRectMake(_avatar.frame.origin.x + _avatar.frame.size.width + 10, 15, 3*_avatar.frame.size.width, nameSize.height + 2);
    }
    
    if (_rankModel.sex != nil) {
        _sexImg.frame = CGRectMake(nameSize.width + _name.frame.origin.x + 7, _name.frame.origin.y, _name.frame.size.height - 3, _name.frame.size.height - 3);
        _sexImg.center = CGPointMake(_sexImg.center.x, _sexImg.center.y + 2);
        _sexImg.backgroundColor =[UIColor whiteColor];
        if ([_rankModel.sex intValue] == 0) {
            _sexImg.image = [UIImage imageNamed:@"aliens_btn"];
        } else if ([_rankModel.sex intValue] == 1) {
            _sexImg.image = [UIImage imageNamed:@"man_btn"];
        } else {
            _sexImg.image = [UIImage imageNamed:@"girl_btn"];
        }
    }
    if (_rankModel.introduce.length == 0 || _rankModel.introduce == nil) {
        _Signature.text = @"这家伙来自外星，还没学会地球语言";
    } else {
        _Signature.text = _rankModel.introduce;
    }
    CGSize signSize = [self changeWorkNameFrame:_Signature.text font:_Signature.font];
    if ([UIScreen mainScreen].bounds.size.height == 736) {
        _Signature.frame = CGRectMake(_name.frame.origin.x, _name.bottom + 10, 5*_avatar.frame.size.width, signSize.height);
    } else if ([UIScreen mainScreen].bounds.size.width == 320) {
        _Signature.frame = CGRectMake(_name.frame.origin.x, _name.bottom + 4, 5*_avatar.frame.size.width, signSize.height);
    } else {
        _Signature.frame = CGRectMake(_name.frame.origin.x, _avatar.frame.origin.y + _avatar.frame.size.height - signSize.height, 5*_avatar.frame.size.width, signSize.height);
    }
    
//    if ([UIScreen mainScreen].bounds.size.height == 736) {
//        [self.attention setFrame:CGRectMake(self.frame.size.width - 50, self.avatar.frame.origin.y, self.frame.size.height / 2, self.frame.size.height / 2)];
//    } else
    if ([UIScreen mainScreen].bounds.size.width == 320) {
        [self.attention setFrame:CGRectMake(self.frame.size.width - 50, self.avatar.frame.origin.y - 8, 25,25)];
    } else {
        [self.attention setFrame:CGRectMake(self.frame.size.width - 50, self.avatar.frame.origin.y, 25, 25)];
    }
    _relation.frame = CGRectMake(self.attention.frame.origin.x - (_attention.frame.size.width / 2), self.attention.frame.origin.y + self.attention.frame.size.height, 40, 12);
    _relation.center = CGPointMake(_attention.center.x, _Signature.center.y);
    self.userId = _rankModel.id;
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *udid = [user objectForKey:@"uid"];
    NSString *relationStr = [NSString stringWithFormat:@"%@", _rankModel.follow];
    self.attention.hidden = NO;
    self.relation.hidden = NO;
    if ([relationStr isEqualToString:@"0"]) {
        if ([_userId isEqualToString:udid]) {
            self.attention.hidden = YES;
            self.relation.hidden = YES;
        }else{
            self.attention.userInteractionEnabled = YES;
            [self.attention setImage:[UIImage imageNamed:@"attention"] forState:UIControlStateNormal];
            self.relation.text = @"加关注";
        }
    }else if ([relationStr isEqualToString:@"1"]){
        self.attention.userInteractionEnabled = NO;
        [self.attention setImage:[UIImage imageNamed:@"didattention"] forState:UIControlStateNormal];
        self.relation.text = @"已关注";
    }else if ([relationStr isEqualToString:@"2"]){
        self.attention.userInteractionEnabled = NO;
        [self.attention setImage:[UIImage imageNamed:@"allattention"] forState:UIControlStateNormal];
        self.relation.text = @"相互关注";
    }

}

-(CGSize)changeWorkNameFrame:(NSString *)workName font:(UIFont *)font
{
    //    CGSize siz = [workName sizeWithFont:[UIFont systemFontOfSize:20] forWidth:[UIScreen mainScreen].bounds.size.width - 20 lineBreakMode:NSLineBreakByWordWrapping];
    CGSize size = CGSizeMake(3*_avatar.frame.size.width, _avatar.frame.size.height / 2);
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    CGRect frame = [workName boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return frame.size;
    //    CGSize labelsize = [workName sizeWithFont:[UIFont systemFontOfSize:20] constrainedToSize:size lineBreakMode:NSLineBreakByWordWrapping];
}
- (void)attention:(UIButton *)sender
{
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"uid"] == nil) {
        //我的
        //提示请先登陆
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"未登录" message:@"登录后才能继续操作" delegate:self cancelButtonTitle:@"再看看" otherButtonTitles:nil];
//        alert.tag = 12345;
//        [alert addButtonWithTitle:@"去登录"];
//        [alert show];
        
        [JCAlertView showTwoButtonsWithTitle:@"未登录" Message:@"登录后才能继续操作" ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"再看看" Click:^{

        } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"去登录" Click:^{
            [[AppDelegate shareDelegate] chooseRootViewController];
        }];
    }else{
        [self requestAttention];
        [self.attention setImage:[UIImage imageNamed:@"关注2"] forState:UIControlStateNormal];
        self.relation.text = @"已关注";
    }
}
- (void)requestAttention
{
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    //    @"http://123.57.1.143/api/tag/ndiscover";//
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/follow", _userId];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    [manager POST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [netWorkManager stopMonitoring];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"rankReload" object:self];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
